package examples;

import com.jom.DoubleMatrixND;
import com.jom.OptimizationProblem;

public class Recubrimiento {

	public static void main(String[] args)
	{
		int N = 6;
		int T = 15;
		double distancia[][] = new double [N][N];
		distancia[0] = new double[] { 0, 10, 20, 30, 30, 20};
		distancia[1] = new double[] {10,  0, 25, 35, 20, 10};
		distancia[2] = new double[] {20, 25,  0, 15, 30, 20};
		distancia[3] = new double[] {30, 35, 15,  0, 15, 25};
		distancia[4] = new double[] {30, 20, 30, 15,  0, 14};
		distancia[5] = new double[] {20, 10, 20, 25, 14,  0};
		
		OptimizationProblem op = new OptimizationProblem();
		
		op.addDecisionVariable( "c", true, new int[] {1,N}, 0, 1);
		
		op.setObjectiveFunction( "minimize", "sum(c)" );
		
		for( int i = 0; i < N; i++ )
		{
			String string = new String();
			boolean control = false;
			
			for( int j = 0; j < N; j++ )
				if( distancia[i][j] <= T )
					if( control == false )
					{
						string += "c(" + j + ")";
						control = true;
					}
					else
						string += " + c(" + j + ")";
				
			
			op.addConstraint( string + " >= 1" );
			System.out.println( string + " >= 1" );
		}
		
	  	op.solve("glpk");

		if (!op.solutionIsOptimal ()) throw new RuntimeException ("An optimal solution was not found");
		
		DoubleMatrixND c = op.getPrimalSolution( "c" );
		System.out.println("c: " + c);
		System.out.println("Total cost obtained: " + op.getOptimalCost());
		
		OptimizationProblem op1 = new OptimizationProblem();
		op1.setInputParameter( "d", distancia );
		op1.setInputParameter( "N", N );
		op1.addDecisionVariable( "x", true, new int[] {N,N}, 0, 1);
		op1.setObjectiveFunction( "minimize", "sum(d .* x)" );
		
		for( int i = 0; i < N; i++ )
			if( c.get( i ) == 0 )
				op1.addConstraint( "sum(x(" + i + ",all)) == 0" );		
		
		op1.addConstraint( "sum(d .* x) >= 1" );
		op1.addConstraint( "sum(x) == N" );
		
		op1.solve("glpk");

		if (!op1.solutionIsOptimal ()) throw new RuntimeException ("An optimal solution was not found");
			
		System.out.println("x: " + op1.getPrimalSolution("x"));
		System.out.println("Total cost obtained: " + op1.getOptimalCost());
	}

}
